var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var session = require("express-session");
const MongoStore = require("connect-mongo");

var indexRouter = require('./routes/web');

const accountRouter = require("./routes/api/account");

const authRouter = require("./routes/web/auth");

const authApiRouter = require("./routes/api/auth");

const {DBHOST, DBPORT, DBNAME} = require("./config/config")

var app = express();


// 配置session
app.use(session({
  name: "session_id", // 设置cookie的name 默认值是：connect.sid
  secret: "Del", // 服务器端生成session的签名
  saveUninitialized: false, // 强制保存未初始化的会话到存储器
  resave: true, // 强制保存已初始化的会话到存储器
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7, // 有效期，单位是毫秒
    httpOnly: true // 限制客户端不能通过document.cookie访问
  },
  store: MongoStore.create({
    mongoUrl: `mongodb://${DBHOST}:${DBPORT}/${DBNAME}`
  })
}))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/', authRouter);
app.use("/api", accountRouter);
app.use("/api", authApiRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.render('404');
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
